package com.penghaonan.appframework.utils.monitor;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;

import com.penghaonan.appframework.AppDelegate;

public class GPSMonitor extends AMonitor<Boolean> {
    private Receiver receiver;
    private final String GPS_ACTION = "android.location.PROVIDERS_CHANGED";
    private final LocationManager locationManager;

    public GPSMonitor() {
        locationManager = (LocationManager) AppDelegate.getApp().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        observeWifiSwitch();
    }

    @Override
    public Boolean getValue() {
        if (locationManager == null) {
            return false;
        }
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return gps || network;
    }

    private void observeWifiSwitch() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(GPS_ACTION);
        receiver = new Receiver();
        AppDelegate.getApp().registerReceiver(receiver, filter);
    }

    /**
     * 释放资源
     */
    @Override
    public void release() {
        if (receiver != null) {
            AppDelegate.getApp().unregisterReceiver(receiver);
        }
    }

    private class Receiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (GPS_ACTION.equals(intent.getAction())) {
                notifyListeners();
            }
        }
    }
}